<template>
  <div ref="chart" class="chart"></div>
</template>

<script>
import * as echarts from "echarts";

export default {
  name: "ECharts",
  props: {
    options: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      chartInstance: null, // 存储 ECharts 实例
    };
  },
  mounted() {
    this.initChart();
    window.addEventListener("resize", this.resizeChart);
  },
  beforeDestroy() {
    window.removeEventListener("resize", this.resizeChart);
    if (this.chartInstance) {
      this.chartInstance.dispose(); // 销毁实例
    }
  },
  watch: {
    options: {
      handler(newOptions) {
        if (this.chartInstance) {
          this.chartInstance.setOption(newOptions); // 更新图表配置
        }
      },
      deep: true,
    },
  },
  methods: {
    initChart() {
      // 初始化 ECharts 实例
      this.chartInstance = echarts.init(this.$refs.chart);
      // 设置初始配置
      this.chartInstance.setOption(this.options);
    },
    resizeChart() {
      if (this.chartInstance) {
        this.chartInstance.resize(); // 调整图表大小
      }
    },
  },
};
</script>

<style scoped>
.chart {
  width: 100%;
  height: 400px; /* 根据需要调整高度 */
}
</style>
